package com.cfw.batch.support;

import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class BatchSupport {

	public static class Config {
		public static final String PROP_FILE_NAME = "config.xml";
	}
	
	private static Properties prop;

	private BatchSupport() { };

	public static String getProperty(String key) { return prop.getProperty(key); }

	public static void log(String msg) {
		System.out.println(
				String.format("%ty-%1$tm-%1$td %1$tH:%1$tM:%1$tS] %s", new java.util.Date(), msg)
				);
	}

	public static void log(String tag, String msg) {
		System.out.println(
				String.format("%ty-%1$tm-%1$td %1$tH:%1$tM:%1$tS] *** [%s] *** %s", new java.util.Date(), tag, msg)
				);
	}
	
	public static void err(String msg) {
		System.err.println(
				String.format("%ty-%1$tm-%1$td %1$tH:%1$tM:%1$tS] %s", new java.util.Date(), msg)
				);
	}
	
	public static void err(String tag, String msg) {
		System.err.println(
				String.format("%ty-%1$tm-%1$td %1$tH:%1$tM:%1$tS] *** [%s] *** %s", new java.util.Date(), tag, msg)
				);
	}
	
	static { init(); }
	
	private static void init() {
		// 프로퍼티 화일은 배치데몬 컨텍스트, WAS 컨텍스트에서 참조되어야 하므로, 두 프로세스 각각의 클래스패스내에  
		// 존재하여야 한다.
		log("initialize", "시작");

		try {
			log("loading properties");
			
			ClassLoader cl = Thread.currentThread().getContextClassLoader();
			
			if (cl == null) { cl = ClassLoader.getSystemClassLoader(); }
			
			URL url = cl.getResource(Config.PROP_FILE_NAME);
			prop = new Properties();
			prop.loadFromXML(url.openStream());
			
			log("property batch url:" + prop.getProperty("url"));
			log("property batch uid:" + prop.getProperty("uid"));
			log("property batch pwd:" + prop.getProperty("pwd"));
		} catch (Exception e) {
			err("loading properties fail");
			e.printStackTrace();
		}
		
		log("initialize", "종료");
	}

	public static Connection getConnection() {
		log("DB connection open");

		Connection cn = null;
		
		try {
			cn = DriverManager.getConnection(
					prop.getProperty("url"), 
					prop.getProperty("uid"), 
					prop.getProperty("pwd"));
			cn.setAutoCommit(false);
		} catch (Exception e) {
			err("DB connection open fail");
			cn = null;
			e.printStackTrace();
		}
		
		return cn; 
	}
	
	public static void closeDBConnection(Connection cn) {
		log("close DB connection");
		
		try {
			if (cn != null) { cn.close(); }
		} catch (Exception e) {
			err("close DB connection fail");
			e.printStackTrace();
		}
	}
	
}
